//app.js
var utilMd5 = require('utils/md5.js');
App({
    //全局初始化
    onLaunch: function () {

        // wx.hideTabBar({

        //   fail: function (err) {

        //     console.log("fail fail fail",err)

        //     setTimeout(function () {

        //       wx.hideTabBar()

        //     }, 500)

        //   }

        // })
        this.getBarInfo()

        let menuButtonObject = wx.getMenuButtonBoundingClientRect();
        wx.getSystemInfo({
            success: res => {
                this.globalData.bottomHeight = res.screenHeight - res.safeArea.bottom;
                this.globalData.model = res.model
                //导航高度
                let statusBarHeight = res.statusBarHeight,
                    navTop = menuButtonObject.top,
                    navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width, // 胶囊按钮与右侧的距离 = windowWidth - right+胶囊宽度
                    navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
                this.globalData.navHeight = navHeight; //导航栏总体高度
                this.globalData.navTop = navTop; //胶囊距离顶部距离
                this.globalData.navObj = menuButtonObject.height; //胶囊高度
                this.globalData.navObjWid = navObjWid; //胶囊宽度(包括右边距离)
                this.globalData.navButtonRight = menuButtonObject.right
                // console.log(navHeight,navTop,menuButtonObject.height,navObjWid)
            },


            fail(err) {
                console.log(err);
            }
        })
    },
    onShow: function (options) {
        let that = this
        //this.redirect('user/myorder', 'type=1')
        console.log(options, 'app onshow', that.globalData.isSuccess, 'that.globalData.isSuccess')
        if (options.referrerInfo.appId == 'wx3e64b506e01256fd') {
            //传的参数在 options.referrerInfo.extraData 里
            //console.log(options.referrerInfo.extraData)
            if (that.globalData.isSuccess == '0') {
                // console.log('调过了')
                return
            }

            var paraArr = new Array();
            paraArr['order_sn'] = that.globalData.pay_order_no;
            var sign = that.signature(paraArr);
            wx.request({
                url: that.globalData.postUrl + '/api/Query',
                data: {
                    order_sn: paraArr['order_sn'],
                    sign: sign
                },
                method: 'POST',
                header: {},
                success: function (res) {
                    console.log('res支付跳转订单查询999', res)
                    if (res.data.code == '1001') {

                        wx.showToast({
                            title: '支付成功',
                            icon: 'none'
                        })

                        setTimeout(() => {
                            that.redirect('user/myorder', 'type=1');
                        }, 1500)

                    } else {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                    }
                    that.globalData.isSuccess = '0'
                }
            })


            return
            if (options.referrerInfo.extraData) {
                if (options.referrerInfo.extraData.data.msg == '支付成功') {
                    that.globalData.isSuccess = '0'
                    // console.log(options,'会返回的信息')
                    var paraArr = new Array();
                    paraArr['order_sn'] = options.referrerInfo.extraData.data.orderNo;
                    var sign = that.signature(paraArr);
                    wx.request({
                        url: that.globalData.postUrl + '/api/Query',
                        data: {
                            order_sn: paraArr['order_sn'],
                            sign: sign
                        },
                        method: 'POST',
                        header: {},
                        success: function (res) {
                            console.log('res支付跳转订单查询1', res)
                        }
                    })
                    wx.showToast({
                        title: '支付成功',
                        icon: 'none'
                    })
                    // wx.showLoading({
                    //   title: '请稍后',
                    // })
                    setTimeout(() => {
                        // wx.hideLoading()
                        console.log(paraArr['order_sn'], paraArr['order_sn'].indexOf('VP', 0), '订单号')
                        if (paraArr['order_sn'].indexOf('VP', 0) > -1) {
                            that.gotaburl('user/index')
                        } else if (paraArr['order_sn'].indexOf('_', 0) > -1) {
                            that.redirect('user/mybalance')
                        } else if (paraArr['order_sn'].indexOf('HH', 0) > -1) {
                            wx.setStorageSync('is_shop', true);
                            that.gourl('hhrCore/index')
                        } else {
                            that.redirect('user/myorder', 'type=-1')
                        }
                    }, 1000)


                } else {
                    that.globalData.isSuccess = '0'
                    wx.showToast({
                        title: options.referrerInfo.extraData.data.msg,
                        icon: 'none'
                    })
                    setTimeout(() => {
                        that.redirect('user/myorder', 'type=-1')
                    }, 2000)
                }
            } else {
                that.globalData.isSuccess = '0'
                wx.showToast({
                    title: '支付失败',
                    icon: 'none'
                })
            }
            // if(options.referrerInfo.extraData.data&&options.referrerInfo.extraData.data.msg=='支付成功'){
            //   wx.showToast({
            //     title: '支付成功',
            //   })
            //   that.redirect('user/myorder', 'type=1')
            // }else{
            //   wx.showToast({
            //     title: '支付失败',
            //   })
            // }
        }
    },
    //授权登录
    login: function (cb) {
        console.log("触发login")
        var that = this;
        var userInfo = that.globalData.userInfo;
        console.log(userInfo, 'userInfo')

        if (userInfo.userID != '') {
            userInfo.is_vip_price = wx.getStorageSync('is_shop') || wx.getStorageSync('is_vip') ? true : false
            wx.setStorageSync('is_vip_price', userInfo.is_vip_price);
            if (userInfo.mobile == null || userInfo.mobile == '') {
                wx.navigateTo({
                    url: '/pages/shouji/shouji',
                })
            }
            typeof cb == "function" && cb(userInfo)
        } else {
            var avatarUrl = wx.getStorageSync('avatarUrl');
            var nickName = wx.getStorageSync('nickName');
            if (avatarUrl != '') { //已授权
                var pid = wx.getStorageSync('pid');
                if (pid == "") {
                    pid = 0;
                }
                //调用登录接口
                wx.login({
                    success: function (res) {
                        var code = res.code;
                        if (code) {
                            //发起网络请求
                            wx.request({
                                url: that.globalData.postUrl + '/api/Logic/WxLogin',
                                data: {
                                    code: code,
                                    // nickname: nickName,
                                    // avatar: avatarUrl,
                                    pid: pid
                                },
                                method: 'GET',
                                header: {},
                                success: function (res3) {
                                    console.log(res3, 222)
                                    // res3.data.success = false
                                    if (res3.data.success) {
                                        // if(res3.data.is_shop){
                                        //   that.globalData.tabBar.list[2].text="合伙人中心"
                                        //   that.globalData.tabBar.list[2].pagePath="/pages/hhrCore/index"
                                        // }
                                        that.editTabbar()
                                        userInfo.openID = res3.data.session_id;
                                        userInfo.userID = res3.data.user_id;
                                        userInfo.isFX = res3.data.is_fx;
                                        userInfo.is_vip_price = res3.data.is_shop || res3.data.is_vip ? true : false
                                        // userInfo.session_key = res3.data.session_key;
                                        wx.setStorageSync('is_vip_price', userInfo.is_vip_price);
                                        wx.setStorageSync('session_key', res3.data.session_key);
                                        wx.setStorageSync('user_id3', res3.data.user_id);
                                        wx.setStorageSync('is_vip', res3.data.is_vip);
                                        wx.setStorageSync('is_shop', res3.data.is_shop);
                                        wx.setStorageSync('shop_name', res3.data.shop_name);
                                        wx.setStorageSync('session_id', res3.data.session_id);
                                        wx.setStorageSync('kefu', res3.data.kefu)
                                    } else {
                                        wx.showModal({
                                            title: '提示',
                                            content: res3.data.msg || '请重新登录',
                                            success(res) {
                                                if (res.confirm) {
                                                    console.log('用户点击确定')
                                                    wx.exitMiniProgram({
                                                        success: function () {
                                                            wx.clearStorageSync()
                                                        }
                                                    })
                                                } else if (res.cancel) {
                                                    console.log('用户点击取消')
                                                }
                                            }
                                        })
                                        return
                                    }

                                    if (res3.data.mobile == null || res3.data.mobile == '') {
                                        wx.navigateTo({
                                            url: '/pages/shouji/shouji',
                                        })
                                    }
                                    userInfo.avatar = avatarUrl;
                                    userInfo.nickName = nickName;
                                    userInfo.mobile = res3.data.mobile;
                                    that.globalData.userInfo = userInfo;
                                    typeof cb == "function" && cb(userInfo)

                                }
                            })
                        } else {
                            console.log('获取用户登录状态失败！' + res2.errMsg)
                        }

                    }
                })
            } else {
                //未授权去授权
                that.redirect('authorize/index');
            }

        }
    },

    // 底部导航
    editTabbar: function () {
        let tabbar = this.globalData.tabBar;
        let currentPages = getCurrentPages();
        let _this = currentPages[currentPages.length - 1];
        let pagePath = _this.route;
        (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
        for (let i in tabbar.list) {
            tabbar.list[i].selected = false;
            (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
        }

        _this.setData({
            tabbar: tabbar
        });
    },

    // 获取顶部信息
    getBarInfo() {
        let menuButtonObject = wx.getMenuButtonBoundingClientRect();
        wx.getSystemInfo({
            success: res => {
                this.globalData.model = res.model
                //导航高度
                let statusBarHeight = res.statusBarHeight,
                    navTop = menuButtonObject.top,
                    navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width, // 胶囊按钮与右侧的距离 = windowWidth - right+胶囊宽度
                    navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
                this.globalData.barInfo.navHeight = navHeight; //导航栏总体高度
                this.globalData.barInfo.navTop = navTop; //胶囊距离顶部距离
                this.globalData.barInfo.navObj = menuButtonObject.height; //胶囊高度
                this.globalData.barInfo.navObjWid = navObjWid; //胶囊宽度(包括右边距离)
                this.globalData.barInfo.navButtonRight = menuButtonObject.right
                // console.log(navHeight,navTop,menuButtonObject.height,navObjWid)
            },
            fail(err) {
                console.log(err);
            }
        })
    },

    /**
     * 签名
     * @param data        提交的数据
     * @returns {string}
     */
    signature: function (data, type) {
        var n = null,
            d = {},
            str = '',
            s = ''
        n = Object.keys(data).sort()
        for (var i in n) {
            d[n[i]] = data[n[i]]
        }
        console.log(d, '加签d');
        for (var k in d) {
            if (d[k] === '') continue
            if (str != '') str += '&'
            str += k + '=' + (type == 1 ? encodeURIComponent(d[k]) : encodeURI(d[k]))
            //  

        }
        // console.log(this.globalData.signKey,'signKey=>')
        str += '&key=' + this.globalData.signKey;
        console.log(str, 'str');

        s = utilMd5.hexMD5(str).toUpperCase() // 这儿是进行MD5加密并转大写
        return s;
    },

    //跳转到不是底部菜单的页面(保存之前页面)
    redirect: function (url, param) {
        wx.navigateTo({
                url: '/pages/' + url + '?' + param,
                fail() {
                    wx.switchTab({
                        url: '/pages/' + url,
                    })
                }
            },

        )
    },
    //跳转到不是底部菜单的页面(关闭之前页面),切换小类要用
    gourl: function (url, param) {
        wx.redirectTo({
            url: '/pages/' + url + '?' + param
        })
    },
    //跳转到底部菜单的页面
    gotaburl: function (url) {
        wx.switchTab({
            url: '/pages/' + url
        })
    },
    globalData: {
        barInfo: {}, // 系统通知栏的信息
        bottomHeight: 0,
        isSuccess: 0,
        pay_order_no: '',
        userInfo: {
            openID: '',
            userID: 0,
            isFX: 0,
            avatar: '',
            nickName: '',
            is_vip_price: false,
        },
        tabBar: {
            "backgroundColor": "#ffffff",
            "color": "#999999",
            "selectedColor": "#f9800f",
            "list": [{
                    "pagePath": "/pages/index/index",
                    "iconPath": "/images/index.png",
                    "selectedIconPath": "/images/index_on.png",
                    "text": "首页"
                },
                {
                    "pagePath": "/pages/goods/category",
                    "iconPath": "/images/fenlei.png",

                    "selectedIconPath": "/images/fenlei_on.png",
                    "text": "礼品"
                },
                // {
                //   "pagePath": "/pages/topic/index",
                //   "iconPath": "/images/huodong_tab.png",
                //   "isSpecial": true,
                //   "text": "活动专区"
                // },
                {
                    "pagePath": "/pages/vipCore/index",
                    "iconPath": "/images/gouwu.png",
                    "selectedIconPath": "/images/gouwu_on.png",
                    "isSpecial": true,
                    "text": "会员中心"
                },
                {
                    "pagePath": "/pages/user/index",
                    "iconPath": "/images/user.png",
                    "selectedIconPath": "/images/user_on.png",
                    "text": "我的"
                }
            ]
        },
        signKey: 'yuehaocc',
        // postUrl: "http://192.168.0.5:85"
        postUrl: "https://lhs.tann.cc"

        // 悦好生活：wx059005de0ca165c8
        //榴皇树  wxf11739412bb0369a
        // 测试  wx238d02fca5c1630c

    }
})